/*************************************************************************
 Copyright (C) Unpublished Unis Software, Inc. All rights reserved.
 Unis Software, Inc., Confidential and Proprietary.

 This software is subject to copyright protection
 under the laws of the Public of China and other countries.

 Unless otherwise explicitly stated, this software is provided
 by Unis "AS IS".
 *************************************************************************/
package com.unis.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 加密工具
 * 
 * @author CSJ (email:raulcsj@163.com)
 * @since 2012-11-16
 */
public final class CryptoUtil {

    private static final Logger LOG = LoggerFactory.getLogger(CryptoUtil.class);

    private static final Properties ENV = new Properties();

    static {
        InputStream in = CryptoUtil.class.getClassLoader().getResourceAsStream("application-shiro.properties");
        try {
            ENV.load(in);
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }
    }

    private CryptoUtil() {}

    private static final String getCombinedSalt(String salt) {
        return ENV.getProperty("shiro.applicationSalt") + ":" + salt;
    }

    private static final Integer getIterations() {
        return Integer.parseInt(ENV.getProperty("shiro.hashIterations"));
    }

    public static final String getRandomSalt() {
        return new SecureRandomNumberGenerator().nextBytes().toBase64();
    }

    public static final String encodePassphrase(String rawPassphrase, String salt) {
        return new Sha512Hash(rawPassphrase, getCombinedSalt(salt), getIterations()).toBase64();
    }

    public static final String encodePassphrase(String rawPassphrase) {
        return encodePassphrase(rawPassphrase, getRandomSalt());
    }

}
